package cn.lbaicai.utils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import cn.lbaicai.entity.Emp;
import cn.lbaicai.entity.User;
import cn.lbaicai.entity.Userrole;
import cn.lbaicai.service.EmpService;
import cn.lbaicai.service.RoleUserService;
import cn.lbaicai.service.UserService;

public class UserRealm extends AuthorizingRealm {
	public Logger log = Logger.getLogger(UserRealm.class);
	@Autowired
	public EmpService empserver;
	@Autowired
	public UserService userservice;
	@Autowired
	private RoleUserService roleUserService;
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		log.info("doGetAuthorizationInfo----->");
		// TODO Auto-generated method stub
		String username = (String) principals.getPrimaryPrincipal();
		User user = new User();
		user.setUsername(username);
		User users = userservice.selectByUser(user);
		List<Userrole> urs = roleUserService.selectByUid(users.getId());
		Set<String> role = new HashSet<String>();
		if(urs.size()>0){
			for(Userrole ur:urs){
				role.add(ur.getRole().getRoleenname());
			}
		}
		
		//role.add("a");
		SimpleAuthorizationInfo authorInfo = new SimpleAuthorizationInfo();
		authorInfo.addRoles(role);
		return authorInfo;
	}

	@SuppressWarnings("unused")
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		log.info("doGetAuthenticationInfo----->");
		String username = (String) token.getPrincipal();
		User user = new User();
		user.setUsername(username);
		User users = userservice.selectByUser(user);
		if(users == null){
			throw new UnknownAccountException();
		}
		 SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(users.getUsername(),
				 users.getPassword(), ByteSource.Util.bytes(users.getCredentialsSalt()), getName());
		return authenticationInfo;
	}

}
